//
//  NotificationService.m
//  GRicePushExtension
//
//  Created by Feng Liu on 2018/9/15.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "NotificationService.h"
#import <AVFoundation/AVFoundation.h>
#import "BDSSpeechSynthesizer.h"
#import "GRiceMacro.h"

static BOOL initializationService = YES;
@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];
    
    // Modify the notification content here...
    NSDictionary *userInfo  = self.bestAttemptContent.userInfo;
    
    NSString *title             = userInfo[@"aps"][@"alert"][@"title"];
    NSString *body            = userInfo[@"aps"][@"alert"][@"body"];
    NSString *action_type   = userInfo[@"action_type"];
    
    self.bestAttemptContent.title = title;
    self.bestAttemptContent.body  = body;
    
    if ([action_type isEqualToString:@"one_pay_notify"]) {
        NSString *content   = userInfo[@"content"];
        [self BDSpeechClient];
        [[BDSSpeechSynthesizer sharedInstance] speakSentence:content withError:nil];
    }

    self.contentHandler(self.bestAttemptContent);
}

- (void)serviceExtensionTimeWillExpire {
    // Called just before the extension will be terminated by the system.
    // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

- (void)BDSpeechClient {
    if (initializationService) {
        [[BDSSpeechSynthesizer sharedInstance] setApiKey:BAIDUKEY withSecretKey:BDSECRETKEY];
        
        [[BDSSpeechSynthesizer sharedInstance] setAudioSessionCategory:AVAudioSessionCategoryPlayback];
        
        [[BDSSpeechSynthesizer sharedInstance] setSynthParam:[NSNumber numberWithUnsignedInt:5] forKey:BDS_SYNTHESIZER_PARAM_VOLUME];
        // 在这里选择不同的离线音库（请在XCode中Add相应的资源文件），同一时间只能load一个离线音库。根据网络状况和配置，SDK可能会自动切换到离线合成。
        NSString* offlineEngineSpeechData = [[NSBundle mainBundle] pathForResource:@"Chinese_And_English_Speech_Female" ofType:@"dat"];
        
        NSString* offlineChineseAndEnglishTextData = [[NSBundle mainBundle] pathForResource:@"Chinese_And_English_Text" ofType:@"dat"];
        
        [[BDSSpeechSynthesizer sharedInstance] loadOfflineEngine:offlineChineseAndEnglishTextData speechDataPath:offlineEngineSpeechData licenseFilePath:nil withAppCode:BAIDUAPPID];

        initializationService = NO;
    }
}


@end
